package cn.fl.mcr.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrLoanAccountQC;
import cn.lionbridgecapital.loan.model.condition.McrLoanChannelQC;
import cn.lionbridgecapital.loan.model.dto.McrLoanAccountDTO;
import cn.lionbridgecapital.loan.service.api.IMcrLoanChannelApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrLoanAccountService;
import cn.fl.mcr.transform.McrLoanChannelVOTransform;
import cn.fl.mcr.vo.McrLoanAccountVO;
import cn.fl.mcr.vo.McrLoanChannelVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSONObject;

/**
 * @Description: 信托账户 控制层
 */
@Controller
@RequestMapping("/mcr/mcrLoanAccount")
public class McrLoanAccountController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrLoanAccountController.class);

	/**
	 * McrLoanAccount 服务层BEAN
	 */
	@Autowired
	private IMcrLoanAccountService mcrLoanAccountService;
	
	@Autowired
	private IMcrLoanChannelApiService publicMcrLoanChannelApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mcr/mcrLoanAccount/mcrLoanAccountList");
		McrLoanChannelQC qc = new McrLoanChannelQC();
		List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(qc));
		view.addObject("channelList", channelList);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrLoanAccount/mcrLoanAccountAdd");
		McrLoanChannelQC qc = new McrLoanChannelQC();
		qc.setIsDel(0);
		qc.setIsValid(1);
		List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(qc));
		view.addObject("id", id);
		view.addObject("channelList", channelList);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do")
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response, McrLoanAccountQC qc) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String creditTmStr = request.getParameter("creditTmStr");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotEmpty(creditTmStr)) {
			//TODO SOMTHING
		}
		if(qc.getAccountBalanceStart() != null){
			qc.setAccountBalanceStart(DecimalUtils.convertYuanToFen(qc.getAccountBalanceStart().doubleValue()));
		}
		if(qc.getAccountBalanceEnd() != null){
			qc.setAccountBalanceEnd(DecimalUtils.convertYuanToFen(qc.getAccountBalanceEnd().doubleValue()));
		}
		page.setCondition(qc);
		Pager pager = this.mcrLoanAccountService.searchListPage(page);
		BaseLogUtils.info(logger, "initList", "查询数据完成>>pager:" + JSONObject.toJSONString(pager), CurrentThreadContext.getCurrentUserName());
		if(pager.getResultList()!=null && pager.getResultList().size()>0){
			List<McrLoanAccountDTO> list = new ArrayList<McrLoanAccountDTO>();
			for (Object obj : pager.getResultList()) {
				McrLoanAccountDTO dto = (McrLoanAccountDTO) obj;
				dto.setAccountBalance(DecimalUtils.convertFenToYuan(dto.getAccountBalance()).longValue());
				dto.setAccountImmovAmount(DecimalUtils.convertFenToYuan(dto.getAccountImmovAmount()).longValue());
				dto.setAccountIniBalance(DecimalUtils.convertFenToYuan(dto.getAccountIniBalance()).longValue());
				dto.setSimgleAmt(DecimalUtils.convertFenToYuan(dto.getSimgleAmt()).longValue());
				dto.setFdAmt(DecimalUtils.convertFenToYuan(dto.getFdAmt()).longValue());//系统余额
				dto.setAvailableBalance(DecimalUtils.convertFenToYuan(dto.getAvailableBalance()).longValue());//可用余额
				if (null != dto.getGuaranteeRateValue()){
					dto.setGuaranteeRateValue(dto.getGuaranteeRateValue() * 100);//担保费率
				}
				list.add(dto);
			}
			BaseLogUtils.info(logger, "initList", "查询数据完成>>list:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
			pager.setResultList(list);
		}
		List<McrLoanAccountVO> list = (List<McrLoanAccountVO>) pager.getResultList();
		ListPageVO<McrLoanAccountVO> listPage = new ListPageVO<McrLoanAccountVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrLoanAccountService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			McrLoanAccountVO vo = this.mcrLoanAccountService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			vo.setAccountBalance(DecimalUtils.convertFenToYuan(vo.getAccountBalance()).longValue());
			vo.setAccountImmovAmount(DecimalUtils.convertFenToYuan(vo.getAccountImmovAmount()).longValue());
			vo.setAccountIniBalance(DecimalUtils.convertFenToYuan(vo.getAccountIniBalance()).longValue());
			vo.setSimgleAmt(DecimalUtils.convertFenToYuan(vo.getSimgleAmt()).longValue());
			if (null != vo.getGuaranteeRateValue()){
				vo.setGuaranteeRateValue(vo.getGuaranteeRateValue() * 100);
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do")
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response, McrLoanAccountVO entity) throws BaseException {
		String accountStartdateStr = request.getParameter("accountStartdateStr");
		String accountEnddateStr = request.getParameter("accountEnddateStr");
		String knotStarttimeStr = request.getParameter("knotStarttimeStr");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			if(!StringUtils.isEmpty(accountStartdateStr)){
				entity.setAccountStartdate(DateUtils.formatStringToDate(accountStartdateStr, "yyyy-MM-dd"));
			}
			if(!StringUtils.isEmpty(accountEnddateStr)){
				entity.setAccountEnddate(DateUtils.formatStringToDate(accountEnddateStr, "yyyy-MM-dd"));
			}
			if(!StringUtils.isEmpty(knotStarttimeStr)){
				entity.setKnotStarttime(DateUtils.formatStringToDate(knotStarttimeStr, "yyyy-MM-dd"));
				entity.setKnotTime(DateUtils.formatStringToDate(knotStarttimeStr, "yyyy-MM-dd"));
			}
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setAccountIniBalance(DecimalUtils.convertYuanToFen(entity.getAccountIniBalance().doubleValue()));
			entity.setAccountImmovAmount(DecimalUtils.convertYuanToFen(entity.getAccountImmovAmount().doubleValue()));
			entity.setSimgleAmt(DecimalUtils.convertYuanToFen(entity.getSimgleAmt().doubleValue()));
			entity.setAccountBalance(entity.getAccountIniBalance());
			entity.setAvailableBalance(entity.getAccountIniBalance());
			McrLoanChannelVO channelVo = McrLoanChannelVOTransform.toVO(publicMcrLoanChannelApiService.selectMcrLoanChannelDTOById(entity.getLoanId()));
			entity.setLoanChannel(channelVo.getLoanChannel());
			if (null != entity.getGuaranteeRateValue()){
				entity.setGuaranteeRateValue(entity.getGuaranteeRateValue() / 100);
			}
			Long id = this.mcrLoanAccountService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do")
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response, McrLoanAccountVO entity) throws BaseException {
		String id = request.getParameter("id");
		String accountStartdateStr = request.getParameter("accountStartdateStr");
		String accountEnddateStr = request.getParameter("accountEnddateStr");
		String knotTimeStr = request.getParameter("knotTimeStr");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			if(!StringUtils.isEmpty(accountStartdateStr)){
				entity.setAccountStartdate(DateUtils.formatStringToDate(accountStartdateStr, "yyyy-MM-dd"));
			}
			if(!StringUtils.isEmpty(accountEnddateStr)){
				entity.setAccountEnddate(DateUtils.formatStringToDate(accountEnddateStr, "yyyy-MM-dd"));
			}
			if(!StringUtils.isEmpty(knotTimeStr)){
				entity.setKnotTime(DateUtils.formatStringToDate(knotTimeStr, "yyyy-MM-dd"));
			}
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			if(entity != null && entity.getLoanId() != null){
				McrLoanChannelVO channelVo = McrLoanChannelVOTransform.toVO(publicMcrLoanChannelApiService.selectMcrLoanChannelDTOById(entity.getLoanId()));
				entity.setLoanChannel(channelVo.getLoanChannel());
			}
			if(entity.getAccountIniBalance() != null){
				entity.setAccountIniBalance(DecimalUtils.convertYuanToFen(entity.getAccountIniBalance().doubleValue()));
			}
			if(entity.getAccountImmovAmount() != null){
				entity.setAccountImmovAmount(DecimalUtils.convertYuanToFen(entity.getAccountImmovAmount().doubleValue()));
			}
			if(entity.getSimgleAmt() != null){
				entity.setSimgleAmt(DecimalUtils.convertYuanToFen(entity.getSimgleAmt().doubleValue()));
			}
			if (null != entity.getGuaranteeRateType() && null != entity.getGuaranteeRateValue() && entity.getGuaranteeRateType().equals(0)) {
				entity.setGuaranteeRateValue(entity.getGuaranteeRateValue() / 100);
			}
			if(null != entity.getGuaranteeRateType() && entity.getGuaranteeRateType().equals(1)){
				entity.setGuaranteeRateValue(null);
			}
			if(null != entity.getIsValid() && entity.getIsValid().equals(BaseConstant.IS_YESNO_NO)){
				McrLoanAccountVO vo = this.mcrLoanAccountService.selectById(Long.valueOf(id));
				if (null != vo.getGuaranteeRateValue()){
					entity.setGuaranteeRateValue(vo.getGuaranteeRateValue());
				}
			}
			boolean success = this.mcrLoanAccountService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	@RequestMapping(value = "/test.do")
	@ResponseBody
	public Object test(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		
		return mcrLoanAccountService.test();
	}
}

